package com.openxt.nbzj.activity;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.RequiresApi;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.WebView;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.openxt.nbzj.R;
import com.openxt.nbzj.model.ConfigModel;
import com.openxt.nbzj.util.SystemUtil;

import org.apache.cordova.engine.SystemWebView;

import java.net.URLEncoder;

import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.onekeyshare.OnekeyShare;
import qs.openxt.libs.activity.OpenxtActivity;
import qs.openxt.libs.progress.Wait;
import qs.openxt.libs.util.StringUtil;
import qs.openxt.libs.util.Utils;

/***
 * 入口主界面
 *
 * @author 赵颖杰 联系方式 13805848274
 */
public class WebViewActivity extends OpenxtActivity implements View.OnClickListener {
    private final String errorUrl = "file:///android_asset/reload.html";
    private boolean isError = false;
    private String url = null;
    private Handler mHandler = new Handler();
    private LinearLayout btn_back = null, btn_close = null;
    private TextView title = null;
    private Context mContext = null;
    private RelativeLayout headerR = null;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        Wait.sharedInstance().start(this, "正在装载页面..., 请稍候");
        url = getIntent().getStringExtra("url");
        if (!url.startsWith("http"))
            url = "file:///android_asset/" + url;
        mContext = this;

        String val = Utils.getLocalStorage(this, ConfigModel.LOGIN_NATIVE);
        if (!StringUtil.isNull(val)) {
            try {
                String[] s = url.split("\\#");
                StringBuilder sb = new StringBuilder();
                sb.append(s[0]).append("?ZJWAPP_COOKIE_USERINFO=").append(URLEncoder.encode(val, "utf8")).append("#").append(s[1]);
                url = sb.toString();
            } catch (Exception e) {
            }
        }

        ShareSDK.initSDK(this);

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                doLoadUrl(url);
            }
        }, 0);
    }

    public void setTitle(String _title) {
        title.setText(_title);
    }

    public void showShareSDK(String param) {
        Utils.setLocalStorage(this, ConfigModel.SHARE_CONTENT, param);
        setupShareRight();
    }

    public void showSearch() {
        setupSearchRight();
    }
    public void hideSearch() {
        LinearLayout right = (LinearLayout) findViewById(R.id.openxt_title_right);
        right.setVisibility(View.VISIBLE);
        right.removeAllViews();
    }

    private void doLoadUrl(String url) {
        super.loadUrl(url);

        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                addHeader();
            }
        }, 0);
    }

    private void addHeader(){
        FrameLayout view = (FrameLayout) findViewById(android.R.id.content);
        headerR = (RelativeLayout) getLayoutInflater().inflate(R.layout.openxt_webview_title, view, false);
        view.addView(headerR);
        title = (TextView) headerR.findViewById(R.id.openxt_title);
        btn_back = (LinearLayout) headerR.findViewById(R.id.openxt_title_left);
        btn_back.setOnClickListener(this);
        btn_close = (LinearLayout) headerR.findViewById(R.id.openxt_title_close);
        btn_close.setOnClickListener(this);
    }

    public Object onMessage(String id, Object data) {
        if ("onReceivedError".equals(id)) {
            try {
                btn_close.setVisibility(View.VISIBLE);
                this.loadUrl(errorUrl);
                isError = true;
            }finally {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Wait.sharedInstance().stop();
                    }
                }, 300);
            }
            return null;
        }else if ("onPageFinished".equals(id)) {
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    Wait.sharedInstance().stop();
                }
            }, 300);
            return null;
        }
        return super.onMessage(id, data);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void onClick(View v) {
        if (v.getId() == R.id.openxt_title_left) {
            if (appView.canGoBack())
                appView.backHistory();
            else
                finish();
        } else if (v.getId() == R.id.openxt_title_close) {
            finish();
        }
    }

    private void setupShareRight() {
        LinearLayout right = (LinearLayout) findViewById(R.id.openxt_title_right);
        right.setVisibility(View.VISIBLE);
        right.removeAllViews();

        View view = LayoutInflater.from(this).inflate(R.layout.right_btn, null);
        view.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));
        right.addView(view);

        ImageView btn = (ImageView) view.findViewById(R.id.right_btn);
        String img = "Content/images/shard.png";
        btn.setImageBitmap(SystemUtil.getImageFromAssetsFile(img, this));

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShare();
            }
        });
    }

    private void setupSearchRight() {
        LinearLayout right = (LinearLayout) findViewById(R.id.openxt_title_right);
        right.setVisibility(View.VISIBLE);
        right.removeAllViews();

        View view = LayoutInflater.from(this).inflate(R.layout.right_btn, null);
        view.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.MATCH_PARENT));
        right.addView(view);

        ImageView btn = (ImageView) view.findViewById(R.id.right_btn);
        btn.setImageResource(R.mipmap.search);

        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                appView.sendJavascript("window.zjwapp.native_search();");
            }
        });
    }

    private void showShare() {
        String param = Utils.getLocalStorage(this, ConfigModel.SHARE_CONTENT);
        if(StringUtil.isNull(param))
            return;
        try{
            JSONObject shareData = JSON.parseObject(param);
            OnekeyShare oks = new OnekeyShare();
            //关闭sso授权
            oks.disableSSOWhenAuthorize();
            oks.setTitle(shareData.getString("title"));
            oks.setTitleUrl(shareData.getString("url"));
            oks.setText(shareData.getString("text"));
            oks.setImageUrl(shareData.getString("image_path"));
            // 启动分享GUI
            oks.show(this);
        }catch (Exception e){

        }
    }

}